package com.yuda.afterexamscore.controller;

import com.yuda.afterexamscore.domain.ThDimensionQuestion;
import com.yuda.afterexamscore.domain.ThQuesTypeAnalysis;
import com.yuda.afterexamscore.service.ISpartaSubjectService;
import com.yuda.afterexamscore.service.IThDimensionQuestionService;
import com.yuda.afterexamscore.utils.SequentialUuidHexGenerator;
import com.yuda.common.core.annotation.Excel;
import com.yuda.common.core.utils.IdUtils;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;
//
/**
 * 题目维度关系Controller
 *
 * @author wyn
 * @date 2021-05-12
 **/
@RestController
@RequestMapping("/thDimensionQuestion")
public class ThDimensionQuestionController extends BaseController
{
    @Autowired
    private IThDimensionQuestionService thDimensionQuestionService;

    @Autowired
    private ISpartaSubjectService spartaSubjectService;

    /**
     * 查询题目维度关系列表
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:list")
    @GetMapping("/list")

    public TableDataInfo list(ThDimensionQuestion thDimensionQuestion)
    {
        startPage();
        List<ThDimensionQuestion> list = thDimensionQuestionService.selectThDimensionQuestionList(thDimensionQuestion);
        for (ThDimensionQuestion t:list
             ) {
            String subjectrelationName = spartaSubjectService.selectSubjectNameById((Long)t.getSubjectRelationId());
            t.setSubjectRealtionName(subjectrelationName);
        }
        return getDataTable(list);
    }

    /**
     * 导出题目维度关系列表
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:export")HttpServletResponse response,
    @Log(title = "题目维度关系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,ThDimensionQuestion thDimensionQuestion) throws IOException
    {

        List<ThDimensionQuestion> list = thDimensionQuestionService.selectThDimensionQuestionList(thDimensionQuestion);
        for(ThDimensionQuestion th:list){
            th.setSubjectName(spartaSubjectService.selectSpartaDescSubjectById(th.getSubjectId()));
            th.setSubjectRealtionName(spartaSubjectService.selectSubjectNameById(th.getSubjectRelationId()));
        }
        ExcelUtil<ThDimensionQuestion> util = new ExcelUtil<ThDimensionQuestion>(ThDimensionQuestion.class);
        util.exportExcel(response, list, "question");
    }
    @PostMapping("/exportExcelModel")
    public void exportExcelModel(HttpServletResponse response) throws IOException {
        //获取系统的环境
        String env = System.getProperty("os.name").toLowerCase();
        String path = "C:\\Users\\61974\\Desktop\\";
        if (env.contains("linux")) {
            path = "/mnt/excelModel/ThDimensionQuestion/";
        }
        String fileName = "DQ_model.xlsx";

        File file = new File(path+fileName);

        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        response.setHeader("Content-Disposition", "attachment; filename=维度.xlsx");
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
    @PostMapping("/import")
    public AjaxResult importToExcel( MultipartFile multipartFile,ThDimensionQuestion thDimensionQuestion) throws Exception {
        InputStream inputStream =  multipartFile.getInputStream();
        ExcelUtil<ThDimensionQuestion> excelUtil = new ExcelUtil<ThDimensionQuestion>(ThDimensionQuestion.class);
        if(multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1).equals("xlsx")) {
            Workbook wb = WorkbookFactory.create(inputStream);
            Sheet sheet = wb.getSheetAt(0);
            String sheetName = sheet.getSheetName();
            wb.close();
            InputStream input = multipartFile.getInputStream();
            //新插入的数据
            List<ThDimensionQuestion> listNew = excelUtil.importExcel(sheetName, input);
            //新插入的数据最后一个参数 进入数据库查询 重新set之后 便于比较
            for (ThDimensionQuestion thd : listNew) {
                thd.getSortNum().trim();
                thd.getDimensionName().trim();
                thd.getQuestionIndex().trim();
//            thd.getQuestionId().trim();
                thd.getSubjectName().trim();
                thd.getSubjectRealtionName().trim();
                if (thd.getSortNum() == null || thd.getSortNum() == "" || thd.getDimensionName() == null || thd.getDimensionName() == "" || thd.getQuestionIndex() == null || thd.getQuestionIndex() == "" || thd.getSubjectName() == null || thd.getSubjectName() == "" || thd.getSubjectRealtionName() == null || thd.getSubjectRealtionName() == "") {
                    return AjaxResult.error("数据表数据错误");
                } else {
                    String[] sub_Arry = thd.getSubjectName().split(":");
                    if (sub_Arry.length > 1) {
                        thd.setSubjectId(spartaSubjectService.selectSpartaSubjectIdbyName(sub_Arry[1], sub_Arry[0]));
                        thd.setSubjectRelationId(spartaSubjectService.selectSpartaSubjectIdbyName(thd.getSubjectRealtionName(), sub_Arry[0]));
                    } else {
                        return AjaxResult.error("数据表数据有错误");
                    }
                }
            }
            //表里原来就有的数据
            List<ThDimensionQuestion> listOld = thDimensionQuestionService.selectThDimensionQuestionList(thDimensionQuestion);
            //处理原来表中的数据
            for (ThDimensionQuestion th : listOld) {
                th.setSubjectName(spartaSubjectService.selectSpartaDescSubjectById(th.getSubjectId()));
                th.setSubjectRealtionName(spartaSubjectService.selectSubjectNameById(th.getSubjectRelationId()));
            }

            //求交集
//        List<ThDimensionQuestion> intersection = listNew.stream().filter(item ->
//                listOld.stream().map(ThDimensionQuestion::changeToString).collect(Collectors.toList()).contains(item.changeToString())
//        ).collect(Collectors.toList());
            //求差集
            List<ThDimensionQuestion> different = listNew.stream().filter(item -> !
                    listOld.stream().map(ThDimensionQuestion::changeToString).collect(Collectors.toList()).contains(item.changeToString())
            ).collect(Collectors.toList());
            if (different.size() != 0) {
                for (ThDimensionQuestion th : different) {
                    th.setUuid(SequentialUuidHexGenerator.generate());
                }
                thDimensionQuestionService.insertThDimensionQuestionList(different);
            } else {
                return AjaxResult.success("插入的数据已存在于数据库中");
            }
        }else{
            return AjaxResult.error("上传文件不是excel格式");
        }
        inputStream.close();
        return AjaxResult.success("操作成功");
    }
    /**
     * 获取题目维度关系详细信息
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:query")
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid)
    {
        return AjaxResult.success(thDimensionQuestionService.selectThDimensionQuestionById(uuid));
    }

//    @GetMapping(value = "/{name}")
//    public AjaxResult getInformation(@PathVariable("name") String name)
//    {
//        return AjaxResult.success(thDimensionQuestionService.selectThDimensionQuestionByName(name));
//    }

    /**
     * 新增题目维度关系
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:add")
    @Log(title = "题目维度关系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ThDimensionQuestion thDimensionQuestion)
    {
        return toAjax(thDimensionQuestionService.insertThDimensionQuestion(thDimensionQuestion));
    }

    /**
     * 修改题目维度关系
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:edit")
    @Log(title = "题目维度关系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ThDimensionQuestion thDimensionQuestion)
    {
        return toAjax(thDimensionQuestionService.updateThDimensionQuestion(thDimensionQuestion));
    }

    /**
     * 删除题目维度关系
     */
//    @PreAuthorize(hasPermi = "afterexamscore:question:remove")
    @Log(title = "题目维度关系", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids)
    {
        return toAjax(thDimensionQuestionService.deleteThDimensionQuestionByIds(uuids));
    }


}
